var phoneReg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;


// pages/index/index.js
// var a = require('../commons/medical.js')
var app = getApp(),
  ids = 1;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    basicNewsList:[{til:"",detail:""}],
    currentTab: 0,
    Show: "none", //管家分类弹出框
    House: "none", //亲友 添加管家 付款 捐赠 帮助 弹出框
    array: [],
    index: 0,
    grade: 0,
    checked: false,
    // annoList: {
    //   code: null
    // },
    //  管家分类假数据
    receive: [{
        ficon: 'sjcrm-daochutonghuajilu',
        title: "指定亲友",
        bind: "clickFri",
        id: 0
      },
      {
        ficon: 'sjcrm-new-customer',
        title: "添加管家",
        bind: "clickAnno",
        id: 1
      },
      {
        ficon: 'sjcrm-yishoukuan',
        title: "付款",
        bind: "clickPay",
        id: 2
      },
      {
        ficon: 'sjcrm-yixiang',
        title: "捐赠",
        bind: "clickDon",
        id: 3
      },
      {
        ficon: 'sjcrm-renwu1',
        title: "帮助与反馈",
        bind: "clickHelp",
        id: 4
      }
    ],
    // 添加管家假数据
    houseList: [{
        title: "服务内容",
        bind: "severText"
      },
      {
        title: "收费标准",
        bind: "chargeText"
      },
      {
        title: "法律提示",
        bind: "legalText"
      }
    ],
    // 建档列表假数据
    List: [
         
    ],
    // 公告假数据
    announCement: [],
  },
  /** 
   * 滑动切换tab 
   */
  bindChange: function(e) {
    this.setData({
      currentTab: e.detail.current
    });
  },
  /** 
   * 点击tab切换 
   */
  swichNav: function(e) {
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      this.setData({
        currentTab: e.target.dataset.current
      })
    }
  },
  // 反馈说明 全局变量
  globaldataIndex:function(){
    var that = this;
    var url = app.util.url('entry/wxapp/instructions')
    app.util.request({
      url: url,
      data: {
        m: 'md_daojia',        
      },
      success: function (res) {        
        console.log(res.data.data)
        app.globalData.globaldataIndex = res.data.data
        console.log("globaldata//////////////////////")
        that.setData({
          newList: app.globalData.globaldataIndex
        })
      }
    })
  },

  onLoad: function(options) {
    var that = this;

    // that.setData({
    //   currentTab: options.currentTab
    // })

    //  高度自适应
    wx.getSystemInfo({
      success: function(res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR - 100;
        that.setData({
          winHeight: calc
        });
      }
    });
    this.archives(options); // 健档 
    this.announCement(options); //公告
    this.globaldataIndex()
  },

  // 跳转法律申明
  btnLegal: function() {
    wx.navigateTo({
      url: '/pages/legalnotice/details',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    var _this = this
    wx.getSystemInfo({
      success: function(res) {
        _this.setData({
          Wheight: res.windowHeight
        })
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },

  //  建立档案请求接口
  archives: function(options) {
    var that = this;
    var url = app.util.url('entry/wxapp/csd')
    app.util.request({
      url: url,
      data: {
        m: 'md_daojia',
        uid: wx.getStorageSync("userInfo")
      },
      success: function(res) {
        var list = res.data.data
        list.basic.bind = 'btnInfo'
        list.cases.bind = 'btnTied'
        list.signs.bind = 'btnSigns'
        list.basic.img1 = '/images/jbinfo.png'
        list.cases.img1 = '/images/minebl.png'
        list.signs.img1 = '/images/wdj.png'
        that.setData({
          List: list
        })
        console.log("建立档案=========>", res);
        // new ================================================
        let newBasic = res.data.data.basic
        let basicNewsList = that.data.basicNewsList
        let tilArr = newBasic.tilArr.split(',')
        let detailArr = newBasic.detailArr.split(',')
        for (let q = 0; q < tilArr.length;q++){
          basicNewsList[q] = {
            til : tilArr[q],
            detail : detailArr[q]
          }          
        }
        that.data.List.basic.basicArr = basicNewsList
        that.setData({
          List: that.data.List,
          basicNewsList: basicNewsList
        })

        setTimeout(function(){
          console.log(that.data.List.basic.title)
          console.log(that.data.List.basic.title == '基本信息')        
        },2000)

      }
    })
  },

  //公告板请求接口
  announCement: function(options) {
    var that = this;
    var url = app.util.url('entry/wxapp/noticelist')
    app.util.request({
      url: url,
      data: {
        m: 'md_daojia',
        uid: wx.getStorageSync('userInfo')
      },
      success: function(res) {
        var list = res.data.data
        list.map(function(index, item) {
          index.bind = 'btnClick'
        })
        that.setData({
          announCement: list
        })
        console.log("公告版=========>", res);
      }
    })
  },


  /*管家打开分类弹窗*/
  showList: function(e) {
    var that = this
    var show = "";
    this.data.Show == "none" ? show = "block" : show = "none"
    this.setData({
      Show: show
    })
  },

  // 指定亲友
  clickFri: function(t) {
    var hide = "";
    var _that = this
    var id = t.currentTarget.dataset.id //判断是否从添加管理点击
    this.data.Show == "block" ? hide = "none" : hide = "none"
    this.setData({
      Show: hide,
      House: 'block',
      idone: id
    })
  },

  // 指定亲友提交表单
  formFriend: function(options) {
    var hide = ''
    var that = this;
    var tels = options.detail.value.friendValue
    var url = app.util.url('entry/wxapp/friend')

    if (tels == "" || tels == undefined) {
      wx.showToast({
        title: '手机号为空',
        icon: 'none'
      })
      return
      
    } else if (!(/^1[3|4|5|7|8][0-9]{9}$/.test(tels))) {
      wx.showToast({
        title: '手机号格式错误',
        icon: 'none'
      })
      return

    } else {
      this.data.House == "block" ? hide = "none" : hide = "none"
      app.util.request({
        url: url,
        data: {
          m: 'md_daojia',
          uid: wx.getStorageSync('userInfo'),
          tel: tels
        },
        success: function(res) {
          var list = res.data.data
          wx.showToast({
            title: res.data.message,
            icon: "none"
          })
          setTimeout(function() {
            that.setData({
              House: hide
            })
          }, 2000)

          console.log("指定亲友=========>", res);
        }
      })
    }

  },

  // 关闭弹窗
  btnCloseqy: function() {
    var _that = this
    console.log("关闭弹窗")
    var hide = ''
    this.data.House == "block" ? hide = "none" : hide = "none"
    _that.setData({
      House: hide
    })
  },

  // 会员卡选项
  bindPickerChange: function(e) {
    let id = e.detail.value
    var _that = this
    var url = app.util.url('entry/wxapp/home')
    id++
    console.log('picker发送选择改变，携带值为', e.detail.value)
    ids = id
    this.setData({
      grade: e.detail.value,
    })

    // 待优化
    app.util.request({
      url: url,
      data: {
        m: 'md_daojia',
        uid: wx.getStorageSync('userInfo'),
        gid: ids
      },
      success: function(res) {
        var list = res.data
        var gradeArray = list.grade
        var arrays = _that.data.array

        console.log(res)
        console.log("==============/////////////////////////////////////////////////////////")

        // gradeArray.map(function(item, index) {
        //   arrays.push(item.members)
        // })
        _that.setData({
          annoList: list,
          array: _that.data.array
        })
      }
    })
  },


  // 单选按钮
  radioChange: function(e) {
    var that = this;
    console.log(e.detail.value)
    e.detail.value == 1 && wx.navigateTo({
      url: '/pages/legalnotice/details',
    })
  },

  // 添加管家提交表单购买
  formHouse: function(options) {
    var hide = "";
    var _that = this
    var url = app.util.url('entry/wxapp/homepay')
    var urlpay = app.util.url('entry/wxapp/hometype')
    var _openid = wx.getStorageSync("openid");
    this.data.House == "block" ? hide = "none" : hide = "none"
    app.util.request({
      url: url,
      data: {
        m: 'md_daojia',
        uid: wx.getStorageSync('userInfo'),
        gid: ids,
        openid: _openid,
        price: _that.data.annoList.silver.price
      },
      success: function(t) {
        console.log("购买管家服务=========>", t);
        wx.requestPayment({
          timeStamp: t.data.data.timeStamp,
          nonceStr: t.data.data.nonceStr,
          package: t.data.data.package,
          signType: t.data.data.signType,
          paySign: t.data.data.paySign,
          success: function(res) {
            console.log("这里是支付成功", res)
            app.util.request({
              url: urlpay,
              cachetime: "0",
              data: {
                m: 'md_daojia',
                orderid: t.data.data.id
              },
              success: function(t) {
                console.log("改变订单状态", t)
                wx.showToast({
                  title: "付款成功",
                  icon: "none",
                  image: "",
                  duration: 2e3,
                  mask: !0,
                  success: function(t) {},
                  fail: function(t) {},
                  complete: function(t) {}
                }), setTimeout(function() {
                  wx.redirectTo({
                    url: '/pages/index/index'
                  })
                }, 2e3);
              }
            });
          },
          fail: function(res) {
            wx.showToast({
              title: "支付失败",
              duration: 1e3
            });
          }
        });
      }
    })
  },

  // 添加管家
  clickAnno: function(t) {
    var hide = "";
    var _that = this
    var url = app.util.url('entry/wxapp/home')
    var id = t.currentTarget.dataset.id //判断是否从添加管理点击
    this.data.Show == "block" ? hide = "none" : hide = "none"
    this.setData({
      Show: hide,
      House: 'block',
      idone: id,
    })
    app.util.request({
      url: url,
      data: {
        m: 'md_daojia',
        uid: wx.getStorageSync('userInfo'),
        gid: ids
      },
      success: function(res) {
        var list = res.data
        var gradeArray = list.grade
        var arrays = _that.data.array
        gradeArray.map(function(item, index) {
          arrays.push(item.members)
        })
        _that.setData({
          annoList: list,
          array: _that.data.array,
          phoneNumber: list.silver.tel
        })
        console.log("添加管家=========>", res, _that.data.array);
      }
    })
  },

  // 呼叫
  btnCall: function() {
    var _that = this
    var url = app.util.url('entry/wxapp/homestate')
    app.util.request({
      url: url,
      data: {
        m: 'md_daojia',
        uid: wx.getStorageSync('userInfo'),
      },
      success: function (res) {
       var codes = res.data.errno
       var phones = String(res.data.data.tel)
        codes == 1 && wx.showToast({
          title: '请添加管家',
          icon: 'none'
        })
        codes == 0 && wx.makePhoneCall({
          phoneNumber: phones //仅为示例，并非真实的电话号码
        })
        console.log("codes", res.data.errno, typeof (phones))
      }
    })

  },

  // 付款
  clickPay: function(t) {
    var hide = "";
    var _that = this
    var id = t.currentTarget.dataset.id //判断是否从添加管理点击
    this.data.Show == "block" ? hide = "none" : hide = "none"
    this.setData({
      Show: hide,
      House: 'block',
      idone: id
    })
  },
  // 付款提交表单
  formPay: function(options) {
    var hide = ''
    this.data.House == "block" ? hide = "none" : hide = "none"
    this.setData({
      House: hide
    })
    console.log("付款转账=========>", options.detail.value)
  },


  // 捐赠
  clickDon: function(t) {
    var hide = "";
    var _that = this
    var id = t.currentTarget.dataset.id //判断是否从添加管理点击
    this.data.Show == "block" ? hide = "none" : hide = "none"
    this.setData({
      Show: hide,
      House: 'block',
      idone: id
    })
  },
  // 捐赠提交表单
  formDonation: function(options) {
    var donationValues = options.detail.value.donationValue
    var _openid = wx.getStorageSync("openid");
    var url = app.util.url('entry/wxapp/donation')
    var urlpay = app.util.url('entry/wxapp/dtype')
    if (donationValues == undefined || donationValues == "") {
      wx.showToast({
        title: '请输入金额',
        icon: 'none'
      })
    } else {
      wx.showLoading({
        title: '支付中',
        success: function() {
          app.util.request({
            url: url,
            data: {
              m: 'md_daojia',
              uid: wx.getStorageSync('userInfo'),
              openid: _openid,
              price: donationValues
            },
            success: function(t) {
              console.log("捐赠支付=========>", t.data);
              wx.requestPayment({
                timeStamp: t.data.data.timeStamp,
                nonceStr: t.data.data.nonceStr,
                package: t.data.data.package,
                signType: t.data.data.signType,
                paySign: t.data.data.paySign,
                success: function(res) {
                  console.log("这里是支付成功", res)
                  app.util.request({
                    url: urlpay,
                    cachetime: "0",
                    data: {
                      m: 'md_daojia',
                      id: t.data.data.id
                    },
                    success: function(t) {
                      console.log("改变订单状态", t)
                      wx.showToast({
                        title: "付款成功",
                        icon: "none",
                        image: "",
                        duration: 2e3,
                        mask: !0,
                        success: function(t) {},
                        fail: function(t) {},
                        complete: function(t) {}
                      }), setTimeout(function() {
                        wx.redirectTo({
                          url: '/pages/index/index'
                        })
                      }, 2e3);
                    }
                  });
                },
                fail: function(res) {
                  wx.showToast({
                    title: "支付失败",
                    duration: 1e3
                  });
                }
              });
            }
          })
        }
      })

    }

    setTimeout(function() {
      wx.hideLoading()
    }, 3e3)

  },
  //  帮助与反馈
  clickHelp: function() {
    wx.navigateTo({
      url: '/pages/help/help',
    })
  },

  // 跳转到基本信息
  btnInfo: function() {
    wx.navigateTo({
      url: '/pages/information/information',
    })

    console.log("基本信息")
  },

  // 跳转到病例
  btnTied: function() {
    wx.navigateTo({
      url: '/pages/cases/cases',
    })
    console.log("病例")
  },
  // 跳转到体征检测
  btnSigns: function() {
    wx.navigateTo({
      url: '/pages/detect/detect',
    })
    console.log("体征检测")
  },

  // 跳转到地图
  btnMap: function() {
    wx.navigateTo({
      url: '/pages/map/map',
    })
  },
  // 预约陪同
  btnAccom: function() {
    wx.navigateTo({
      url: '/pages/appointment/appointment',
    })
  },
  // 预约挂号
  btnRegistered: function() {
    wx.navigateTo({
      url: '/pages/registered/registered',
    })
  },
  // 跳转公告详情
  btnClick: function(e) {
    var announCement = this.data.announCement
    var index = e.currentTarget.dataset.index
    announCement.map(function(item, indexs) {
      indexs == index ? wx.navigateTo({
        url: '/pages/announcement/details?id=' + item.id,
      }) : ""
    })
    console.log("index======>", index)
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.archives(); // 健档 
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})